<template>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      highlight-current-row
      @current-change="handleCurrentChange"
    >
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="合同编号" align="center" prop="htid" />
      <el-table-column label="合同名称" align="center" prop="htmc" />
      <el-table-column label="合同类型" align="center" prop="htlx">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONT_HTLX" :value="scope.row.htlx" />
        </template>
      </el-table-column>
      <el-table-column label="合同类别" align="center" prop="htlb">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONT_HTLB" :value="scope.row.htlb" />
        </template>
      </el-table-column>
      <el-table-column label="二维码/条形码" align="center" prop="ewm">
        <template #default="scope">
          <img v-if="scope.row.ewm" :src="scope.row.ewm" class="h-30px" @click="imagePreview(scope.row.ewm)"/>
        </template>
      </el-table-column>
      <el-table-column label="合同金额" align="center" prop="htje" />
      <el-table-column
        label="服务开始时间"
        align="center"
        prop="kssj"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="服务结束时间"
        align="center"
        prop="jssj"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="项目名称" align="center" prop="xmmc" />
      <el-table-column label="部门" align="center" prop="bm" />
      <el-table-column label="负责人" align="center" prop="fzr" />
      <el-table-column label="合同执行方式" align="center" prop="zxfs" />
      <el-table-column label="合同主要内容" align="center" prop="zynr" />
      <el-table-column label="付款方式" align="center" prop="fkfs">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONT_FKFS" :value="scope.row.fkfs" />
        </template>
      </el-table-column>
      <el-table-column label="客户单位" align="center" prop="khdw" />
      <el-table-column label="客户联系人" align="center" prop="khlxr" />
      <el-table-column label="合同状态" align="center" prop="htzt">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONT_HTZT" :value="scope.row.htzt" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="bz" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="签订时间"
        align="center"
        prop="qdsj"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="线号" align="center" prop="xid" />
      <el-table-column label="A端地址" align="center" prop="jrdd" />
      <el-table-column label="Z端地址" align="center" prop="scdd" />
      <!-- <el-table-column label="操作" align="center" fixed="right" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['cont:base-info:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['cont:base-info:delete']"
          >
            删除
          </el-button>
          <el-button
            link
            type="warning"
            @click="openForm('check', scope.row.id)"
            v-hasPermi="['cont:base-info:check']"
          >
            查看
          </el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" fixed="right" width="80px">
        <template #default>
          <el-button
            link
            type="warning"
            @click="processDialogVisible = true"
            v-hasPermi="['cont:base-info:check']"
          >
            处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BaseInfoForm ref="formRef" @success="getList" />
  <!-- 子表的列表 -->
  <ContentWrap>
    <el-tabs model-value="detailInfo">
      <el-tab-pane label="建设合同详细信息" name="detailInfo">
        <DetailInfoList :htid="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="合同资料表 " name="materialInfo">
        <MaterialInfoList :htid="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="合同收付款记录表 " name="payInfo">
        <PayInfoList :htid="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="合同变更记录表 " name="changeInfo">
        <ChangeInfoList :htid="currentRow.id" />
      </el-tab-pane>
      <el-tab-pane label="合同收付款计划表 " name="planInfo">
        <PlanInfoList :htid="currentRow.id" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>

  <!-- 处理弹窗 -->
  <Dialog :title="processDialogTitle" v-model="processDialogVisible">
    <el-form ref="processFormRef" :model="processFormData" label-width="100px">
      <el-form-item label="提醒方式" prop="remindType">
        <el-select v-model="processFormData.remindType" placeholder="请选择提醒方式">
          <el-option label="邮件提醒" value="email"/>
          <el-option label="短信提醒" value="sms"/>
          <!-- <el-option label="电话" value="phone"/> -->
        </el-select>
      </el-form-item>
      <el-form-item label="提醒内容" prop="remindContent">
        <el-input type="textarea" v-model="processFormData.remindContent" placeholder="请输入提醒内容"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="processDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleProcess">确 定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as BaseInfoApi from '@/api/cont/base'
import BaseInfoForm from './BaseInfoForm.vue'
import DetailInfoList from './components/DetailInfoList.vue'
import MaterialInfoList from './components/MaterialInfoList.vue'
import PayInfoList from './components/PayInfoList.vue'
import ChangeInfoList from './components/ChangeInfoList.vue'
import PlanInfoList from './components/PlanInfoList.vue'
import { createImageViewer } from '@/components/ImageViewer'

import { ref } from 'vue';
import { ElMessage } from 'element-plus';

defineOptions({ name: 'BaseInfo' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  htid: undefined,
  htmc: undefined,
  htlx: undefined,
  htlb: undefined,
  kssj: undefined,
  kssj: [],
  jssj: undefined,
  jssj: [],
  fkfs: undefined,
  khdw: undefined,
  khlxr: undefined,
  htzt: undefined,
  createTime: [],
  qdsj: undefined,
  qdsj: [],
  xid: undefined,
  jrdd: undefined,
  scdd: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 格式化日期为 "yyyy-MM-dd HH:mm:ss"
const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 获取当前日期和一周前的日期
const today = new Date();
const AfterOneWeek = new Date(today);
AfterOneWeek.setDate(today.getDate() + 7);
// 使用 ref 创建响应式数据
const dateRange = ref<string[]>([
  formatDate(today) + ' 00:00:00',
  formatDate(AfterOneWeek) + ' 23:59:59',
]);
// 在组件挂载后打印 dateRange 值
// onMounted(() => {
//   console.log(dateRange.value);
// });

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BaseInfoApi.getBaseInfoPage({pageNo: 1,pageSize: 10,jssj:dateRange.value})
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BaseInfoApi.deleteBaseInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BaseInfoApi.exportBaseInfo(queryParams)
    download.excel(data, '合同基础信息表 .xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中行操作 */
const currentRow = ref({}) // 选中行
const handleCurrentChange = (row) => {
  currentRow.value = row
}

/** 图片预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

const processDialogVisible = ref(false);
const processDialogTitle = '处理操作';
const processFormData = reactive({
  remindType: '',
  remindContent: ''
});
const processFormRef = ref(null);

// 打开处理弹窗并重置表单数据
const openProcessDialog = () => {
  resetFormData();
  processDialogVisible.value = true;
};

// 关闭处理弹窗并重置表单数据
const closeProcessDialog = () => {
  processDialogVisible.value = false;
  resetFormData();
};

// 处理用户的输入
const handleProcess = () => {
  console.log('处理操作:', processFormData);
  processDialogVisible.value = false;
  ElMessage.success('发送成功');
  resetFormData();
};

// 重置表单数据
const resetFormData = () => {
  processFormData.remindType = '';
  processFormData.remindContent = '';
};

/** 初始化 **/
onMounted(() => {
  getList()
})

</script>